/**
 * 政策详情分页js
 * 
 */

var pageNum = 1;
var itemNum = 20;
var insretPolicy = document.getElementById("insretPolicy");
var countNum = 0;

(function($) {

	mui.init({
		pullRefresh: {
			container: '#content',
			down: {
				style: 'circle',
				callback: pulldownRefresh
			},
			up: {
				auto: true,
				contentrefresh: '正在加载...',
				callback: pullupRefresh
			}
		}
	});
	setPxPerRem();
	mui.plusReady(function() {
		var clientWidth = getQueryString("clientWidth");
		setPxPerRem(clientWidth);
	});

})(mui);

//下拉刷新
var isRefresh = false;

function pulldownRefresh() {
	removeLi("policyList");
	isRefresh = true;
	pageNum = 1;
	if(isHaveNet()) {
		getPoilcyList();
	} else {
		mui.toast("无网络连接！");
	}
}

//上拉加载
var isLoad = false;

function pullupRefresh() {
	isLoad = true;
	if(isHaveNet()) {
		getPoilcyList();
	} else {
		mui.toast("无网络连接！");
	}
}

function getPoilcyList() {
	var jsonData = {
		page: pageNum,
		per_page: itemNum,
	}

	checkParams(jsonData);

	var opts = {
		url: '/policy',
		addressUrl: "testline",
		requestType: "GET",
		pastDate: jsonData
	}

	crossDomainAjax(opts, function(data) {

		toastMesg(data, 10000, 20000);

		if(!isEmpty(data)) {
			var rows = data.data;
			if(!isEmpty(rows)) {
				for(var i = 0; i < rows.length; i++) {
					createPolicyItem(rows[i]);
				}
			} else {
				mui.toast("获取数据失败！");
			}

		} else {
			mui.toast("获取数据失败！");
		}

		if(isRefresh) {
			mui('#content').pullRefresh().endPulldown();
			isRefresh = false;
		}

		if(isLoad) {
			isLoad = false;
			mui('#content').pullRefresh().endPullup((pageNum > countNum));
		}
		plus.nativeUI.closeWaiting();
		if(pageNum == 1) {
			showEle(content);
			mui('#content').pullRefresh().endPullup(false);
		}
		pageNum++;

	});
}

/**
 * 创建政策列表
 * @param {Object} row
 */
function createPolicyItem(row) {

	var createLi = document.createElement("li");

	if(isEmpty(row.thumb)) {
		row.thumb = "../../ui/building/images/08policy/02.jpg";
	}
	var createTime =  row.created_at.substr(0 , 10);

	createLi.id = row.id;
	createLi.className = "mui-table-view-cell";
	createLi.innerHTML = '<img src="' + row.thumb + '" />' +
		'<p class="policy-title">' + row.title + '</p>' +
		'<div class="item-bottom">' +
		'<p class="left">' + createTime + '</p>' +
		'<p class="right"><span>' + row.browsed + '</span>次浏览</p>' +
		'</div>';
	document.body.appendChild(createLi);
	insertBefore(createLi, insretPolicy);

	mui("#policyList").on('click', 'li', function() {
		var postdata = {
			pageflag: "page_policy.html",
			itemID: this.id
		}

		var change = {
			pageUrl: "page_policyinfo.html",
			postData: postdata,
			aniShow: "fade-in"
		}
		
		pageChange(change);

	});
}